package com.wang.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.wang.gulimall.order.config.AlipayTemplate;
import com.wang.gulimall.order.service.OrderService;
import com.wang.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 订单支付成功监听器 支付宝服务器的异步通知关闭本系统的订单
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-07-08 17:39
 **/

@RestController
@Slf4j
public class OrderPayedListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    //买家账号  ccbigv3199@sandbox.com
    //登录密码111111
    //支付密码111111

    //支付成功后接收支付宝服务器的异步通知，同时更改订单状态
    //服务器[异步通知]页面路径
    @PostMapping(value = "/payed/notify")  //支付宝异步回调地址
    public String handleAlipayed(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 只要收到支付宝的异步通知，返回 success 支付宝便不再通知
        // 获取支付宝POST过来反馈信息
        //TODO 需要验签
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //核心操作 验证签名 验证是否是支付宝给我们系统发送回来的数据
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified) {
            log.error("订单服务调用支付宝SDK验证签名成功");
            //去修改订单状态  这里需要返回success不然的话支付宝服务器会不断重复给我们发送异步通知消息
            String result = orderService.handleAliPay(asyncVo);
            return result;
        } else {
            log.error("失败订单服务调用支付宝SDK验证签名");
            return "error";
        }
    }

    @PostMapping(value = "/pay/notify")
    public String asyncNotify(@RequestBody String notifyData) {
//        //异步通知结果
//        return orderService.asyncNotify(notifyData);
        return null;
    }
}
